<template>
  <div v-if="subParams.isHistoryData" class="subform-search-content">
    <div class="subform-search-item" style="box-shadow: 2px 2px 2px 0 rgba(221,225,234,0.3);">
      <div class="subform-search-text">历史记录</div>
      <i class="el-icon-close" @click="close()" />
    </div>
    <div>
      <div v-loading="loading" style="min-height: 32px;">
        <div v-if="value.fieldValue && !list.length" class="subform-search-item no-data">暂无数据</div>
        <template v-else>
          <div v-for="(item, index) in list" :key="`${item['_id']}${index}}`" class="subform-search-item">
            <div class="subform-search-text" @click="handleSelect(item)">
              <ToolTip :content="format(item)" />
            </div>
            <i class="el-icon-delete" @click="handleDelete(item._id)" />
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import { deleteSubformHistory, getSubformHistory } from '@/api/process';
import { standardFormat } from '@/filters/date';

export default {
  name: 'SubSearchView',
  /* model: {
    prop: 'value',
    event: 'changeValue'
  }, */
  props: {
    value: {
      type: Object,
      default: () => ({})
    },
    rowId: {
      type: String,
      default: ''
    },
    subParams: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      list: [],
      loading: false
    };
  },
  watch: {
    value: {
      handler(val) {
        this.debounceRequest(val);
      },
      deep: true
    }
  },
  created() {
    this.getSubformHistoryData(this.value);
  },
  methods: {
    standardFormat,
    handleSelect(data) {
      data.rowId = this.rowId;
      this.$emit('selectHistory', data);
    },
    handleDelete(id) {
      this.$confirm('请确认是否删除所选的数据', '', {
        confirmButtonText: '确定', type: 'warning',
        showClose: false, center: true, iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        deleteSubformHistory({ id, subFormKey: this.subParams.key }).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.getSubformHistoryData(this.value);
            this.$emit('deleteSubHistory');
          }
        }).catch(err => console.error(err.message));
      });
    },
    dataFormat(item, data) {
      if (item.type === 'date') {
        const formatMap = new Map([['yyyy/MM', 'YYYY-DD'], ['yyyy/MM/dd', 'YYYY-MM-DD'], ['yyyy/MM/dd HH:mm:ss', 'YYYY-MM-DD HH:mm:ss']]);
        const format = formatMap.get(item.options.format);
        return this.standardFormat(data / 1000, format).replace(/-/g, '/');
      }
      if (item.type === 'switch') {
        return data ? '是' : '否';
      }
      if (item.type === 'user') {
        return data.userName;
      }
      if (item.type === 'post') {
        return data.name;
      }
      if (item.type === 'department') {
        const dataType = data instanceof Array;
        return dataType ? data.map(it => it.name).join(',') : data.name;
      }
      if (item.type === 'upAttachment') {
        return data.map(it => it.name).join(',');
      }
      return data;
    },
    sort(data) {
      const result = [];
      if (this.subParams.subform.length) {
        this.subParams.subform.map(it => {
          const res = this.dataFormat(it, data[it.key]);
          result.push(res);
        });
      }
      return result;
    },
    format(obj) {
      const temp = this.sort(JSON.parse(JSON.stringify(obj)));
      return temp.join('，');
    },
    getSubformHistoryData(value) {
      this.loading = true;
      let params = {
        subFormKey: this.subParams.key,
        page: 1,
        perPage: 3
      };
      if (value.fieldValue) {
        params = { ...value, ...params };
      }
      getSubformHistory(params).then(res => {
        if (res.code === 200) {
          this.list = res.data;
          this.loading = false;
        }
      }).catch(err => {
        this.loading = false;
        console.error(err.message);
      });
    },
    close() {
      this.$emit('close');
    },
    debounceRequest: _.debounce(function(val) {
      // 节流搜索
      this.getSubformHistoryData(val);
    }, 500)
  }
};
</script>

<style lang="scss" scoped>
.subform-search-content {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 3px 6px 0 #caccd4;
  margin-top: 3px;
  .subform-search-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 34px;
    font-size: 14px;
    color: #606266;
    padding: 0 8px;
    cursor: pointer;
    &:hover {
      color: #406eff!important;
      background-color: #f5f7fa;
    }
    .subform-search-text {
      flex: 1;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
    &.no-data {
      justify-content: center;
    }
  }
}
</style>
